package com.jubaozan.service.platform.decorator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jubaozan.c3.framework.utils.MD5Util;
import com.jubaozan.c3.framework.utils.ObjectUtil;
import com.jubaozan.c3.framework.utils.ResultHolder;
import com.jubaozan.c3.framework.utils.ResultStatus;
import com.jubaozan.dao.youme.domain.SysUser;
import com.jubaozan.dao.youme.service.SysUserService;
import com.jubaozan.feign.login.LoginFeignService;
import com.jubaozan.feign.login.vo.TokenMetaVO;
import com.jubaozan.feign.login.vo.TokenVO;
import com.jubaozan.service.platform.constants.PlatformConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: chenjingui
 * @Date: 2020/9/23 18:53
 * @Description:
 */
@Slf4j
@Component
public class PlatformUserDecorator {
    @Autowired
    private LoginFeignService loginFeignService;
    @Autowired
    SysUserService sysUserService;
    private static final String TOKEN_SECRET ="1122334455";
    private static final String APP_ID =" SUP";
    private static final String SUPPLIER_TYPE = "0";


    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResultHolder register(SysUser sysUser) throws Exception {

        //判断是否已经注册
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",sysUser.getUsername());
        if(ObjectUtil.isNotEmpty(sysUserService.listObjs(queryWrapper))){
            return ResultHolder.error(ResultStatus.USER_PHONE_ERROR, "该手机号码已被注册");
        }
     //添加项目方 注册对象
        boolean result = sysUserService.save(sysUser);
        return ResultHolder.success(result);
    }
    /**
     * 平台用户登录系统
     * @param mobile 手机
     * @param pwd 密码
     * @return
     */
    public ResultHolder login(String  mobile, String pwd){
        //参数校验
        if(StringUtils.isBlank(mobile) || StringUtils.isBlank(pwd)){
            return ResultHolder.error(ResultStatus.SYSTEM_ERROR, "参数错误");
        }
        //校验用户名个密码
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",mobile);
        queryWrapper.eq("password",MD5Util.digest(pwd));
        queryWrapper.eq("account_type",0);
        SysUser user = sysUserService.getOne(queryWrapper);
        if(null == user){
            return ResultHolder.error(ResultStatus.USER_PHONE_ERROR, "用户名或者密码错误");
        }
        ResultHolder<TokenVO> backendToken = loginFeignService.createBackendToken("SUP", TOKEN_SECRET, "SUP",
                0001L, mobile);
        return backendToken ;
    }
}
